package com.cooksys.film_rental.dao.impl;

import java.io.Serializable;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.cooksys.film_rental.dao.UserDao;
import com.cooksys.film_rental.model.Customer;
import com.cooksys.film_rental.model.User;

@Repository("UserDao")
@Transactional
public class UserDaoImpl implements UserDao {

	@Autowired(required = true)
	private SessionFactory sessionFactory;

	/**
	 * 
	 * @return the current session from the internal {@link SessionFactory}
	 */
	public Session currentSession() {
		return sessionFactory.getCurrentSession();
	}

	@Override
	public User getUserByUserId(String userId) {
		Session session = currentSession();

		String hql = "from User u where u.userId = :userId";
		Query query = session.createQuery(hql);
		query.setString("userId", userId);

		return (User) query.uniqueResult();
	}

	@Override
	public User getUserByCustomerId(Short customerId) {
		Session session = currentSession();

		String hql = "from User u where u.customerId = :customerId";
		Query query = session.createQuery(hql);
		query.setShort("customerId", customerId);

		return (User) query.uniqueResult();
	}

	@Override
	public User getUserByCustomer(Customer customer) {
		Session session = currentSession();

		String hql = "from User u where u.customer = :customer";
		Query query = session.createQuery(hql);
		query.setEntity("customer", customer);

		return (User) query.uniqueResult();
	}

	@Override
	public User save(User user) {
		Session session = currentSession();
		Serializable id = session.save(user);
		return (User) session.get(User.class, id);
	}

}
